package springsecurity.utlis;

import lombok.AllArgsConstructor;
import org.springframework.util.AntPathMatcher;
import org.thymeleaf.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 *
 * @User: c.c
 * @Date: 2022/6/14
 * @Time: 14:05
 * @Description: 权限缓存
 */

public final class AuthCache {

    //单例模式
    public static final AuthCache AUTH_CACHE = new AuthCache();

    /**
     * 动态URI的权限集合（带有*号的）
     */
    private final List<OneAuth> dynamicAuthList = new ArrayList<>();


    /**
     * 所有有效的权限集合
     */
    private final Map<String, OneAuth> authMap = new HashMap<>();

    /**
     * 固定URI的权限集合
     */
    private final List<OneAuth> fixedAuthList = new ArrayList<>();

    /**
     * 地址检查器
     */
    private final AntPathMatcher pathMatcher = new AntPathMatcher("/");

    private AuthCache() {
    }

    /**
     * 获取实例
     *
     * @return AuthCache
     */
    public static AuthCache getInstance() {
        return AUTH_CACHE;
    }

    public String getAuthName(String id){
        final OneAuth oneAuth = authMap.get(id);
        if (oneAuth != null) {
            return oneAuth.name;
        }
        return null;
    }
    public String matcher(String method, String uri) {

        for (OneAuth oneAuth : fixedAuthList) {
            if (StringUtils.equalsIgnoreCase(oneAuth.method, method)
                    && StringUtils.equals(oneAuth.uri, uri)) {
                //匹配时直接返回
                return oneAuth.id;
            }
        }
        //匹配动态URI
        for (OneAuth oneAuth : dynamicAuthList) {
            if (StringUtils.equalsIgnoreCase(oneAuth.method, method)
                    && pathMatcher.match(oneAuth.uri, uri)) {
                //匹配时直接返回
                return oneAuth.id;
            }
        }
        return null;
    }

    @AllArgsConstructor
    static class OneAuth {
        private final String id;
        private final String name;
        private final String uri;
        private final String method;
    }
}
